from typing import *
from math import inf


class Solution:
    def closestMeetingNode(self, edges: List[int], node1: int, node2: int) -> int:
        n = len(edges)
        dp = [[inf] * 2 for _ in range(n)]

        def f(node, h, t):
            if node == -1 or dp[node][t] < inf:
                return
            dp[node][t] = h
            f(edges[node], h + 1, t)

        f(node1, 0, 0)
        f(node2, 0, 1)
        ans = inf
        ai = -1
        for i, (a, b) in enumerate(dp):
            if (c := max(a, b)) < ans:
                ans = c
                ai = i

        return ai
